#pragma once

#include <iostream>
#include <unistd.h>
#include <memory.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>

class Socket{
public:
  static int SocketCreate();
  static void SocketBind(int sock, int port);
  static void SocketListen(int sock, int backlog);
};

int Socket::SocketCreate(){
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    std::cerr << "socket error" << std::endl;
    exit(2);
  }

  // 设置端口复用
  int opt = 1;
  setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  std::cout << "SocketCreate success" << std::endl;
  return sockfd;
}

void Socket::SocketBind(int sock, int port) {
  struct sockaddr_in local;
  memset(&local, 0, sizeof(local));
  local.sin_family = AF_INET;
  local.sin_port = htons(port);
  local.sin_addr.s_addr = INADDR_ANY;

  socklen_t len = sizeof(local);
  if (bind(sock, (struct sockaddr*)&local, len) < 0) {
    std::cerr << "bind error" << std::endl;
    exit(3);
  }
  std::cout << "SocketBind success" << std::endl;
}


void Socket::SocketListen(int sock, int backlog) {
  if (listen(sock, backlog) < 0) {
    std::cerr << "listen error" << std::endl;
    exit(4);
  }
  std::cout << "SocketListen success" << std::endl;
}




